import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart' show required, compute;
import 'package:ibooks/model/index.dart';

class BookDecoder {
  BookDecoder({@required this.content, @required this.chapters})
      : assert(null != content),
        assert(null != chapters);

  static Book _book;

  final String content;
  final List<Chapter> chapters;

  static Future<BookDecoder> decode(Book book) async {
    print('decode ${book.name}...');
    Map<String, dynamic> data;

    _book = book;
    try {
      switch (book.type) {
        case "TEXT":
          data = await compute(_decodeText, book.path);
          break;
        default:
      }
      print('decode complete');
    } catch (e) {
      print('decode err: $e');
      throw e;
    }
    return new BookDecoder(
        content: data['content'], chapters: data['chapters']);
  }

  int get maxLength => content?.length;

  dynamic getSection(int offset, int length, {bool raw: false}) {
    print('get section offset=$offset length=$length');
    print('content.length = ${content.length}');
    String text;
    if (!(offset >= 0) || !(length > 0)) {
      return null;
    }
    if (offset >= maxLength) {
      return null;
    }
    if (offset + length >= maxLength) {
      text = content.substring(offset, maxLength);
    } else {
      text = content.substring(offset, offset + length);
    }
    if (true == raw) {
      return text;
    } else {
      return new Section(title: 'title...', content: text);
    }
  }

  /// free the memory
  void close() {}
}

Future<Map<String, dynamic>> _decodeText(String uri) async {
  try {
    File file = new File(uri);
//    RandomAccessFile randomAccessFile = file.openSync(mode: FileMode.READ);
    String charset = 'utf8';
    String content = '';
    List<Chapter> chapters = <Chapter>[];
    switch (charset) {
      case 'gbk':
        throw new Exception('gbk格式暂不支持');
        break;
      case 'utf8':
        content = utf8.decode(await file.readAsBytes(), allowMalformed: true);
        break;
      case 'latin1':
        content = latin1.decode(file.readAsBytesSync());
        break;
      default:
        throw new Exception('不支持的文件格式');
    }
//    randomAccessFile.close();
    return {'content': content, 'chapters': chapters};
  } catch (e) {
    print('decode text err: $e');
    throw e;
  }
}


String charsetDetector(RandomAccessFile file) {
  String charset;
//  List<int> bytes = file.readSync(3);
//  int length = file.lengthSync();
//  bool isLatin1 = true;
//  bool isUtf8 = true;
//  if (null != bytes &&
//      bytes.length == 3 &&
//      bytes[0] == 0xEF &&
//      bytes[1] == 0xBB &&
//      bytes[2] == 0xBF) {
//    isLatin1 = false;
//  } else if (null != bytes && bytes.isNotEmpty) {
//    //不带bom头，可能是gbk,latin1,utf8,big5
//    bytes = file.readSync(100 > length ? length : 100);
//    int i = 0;
//    do {
//      if (bytes[i] > 127) {
//        isLatin1 = false;
//      }
//      if ((bytes[i] & 0xC0) != 0x80) {
//        isUtf8 = false;
//      }
//      i++;
//    } while (i < bytes.length);
//  }
//  if (!isLatin1 && !isUtf8) {
//    charset = 'gbk';
//  } else if (!isLatin1 && isUtf8) {
//    charset = 'utf8';
//  } else if (isLatin1 && !isUtf8) {
//    charset = 'latin1';
//  }
  charset = 'utf8';
  return charset;
}
